# -*- coding: utf-8 -*-
# @file   : HboUpdate.py
# @author : songxulin
# @date   : 2021:08:20 14:00:00
# @version: 1.0
# @desc   : python自动更新exe
import os
import urllib.request
import base64
import datetime
import time
import json
import winreg
from hboMonitor import ComputerInfo

# 公共目录
directory = "C:/HboSoft"


def create_exe_file(url, file_name):
    """创建文件"""
    try:
        if not os.path.exists(directory):
            os.mkdir(directory)
        # 更新替换文件前需停止待更新程序
        os.system('taskkill /f /t /im %s.exe' % file_name)
        if not url:
            return "url is null"
        b64_text = get_data_by_url(url)
        exe_file_path = "%s/%s.exe" % (directory, file_name)
        f = open(exe_file_path, 'wb+')
        f.write(base64.b64decode(b64_text))
        f.close()
    except IOError:
        return "cannot open url"
    except Exception as e:
        return "fail"+e.__doc__
    return "success"


def run_exe(file_name):
    """启动程序"""
    os.system('start "" "%s/%s.exe"' % (directory, file_name))


def get_data_by_url(url):
    """获取远程数据"""
    header = {
        'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }  # 头部信息
    request = urllib.request.Request(url=url, headers=header)  # 请求处理
    b64_text = urllib.request.urlopen(request).read()  # 读取结果
    return b64_text


def read_version_json():
    """读取本地版本文件"""
    if not os.path.exists("%s/version.json" % directory):
        return {}

    with open("%s/version.json" % directory, mode='r', encoding='utf-8') as j:
        return json.load(j)


def write_version_json(data):
    """更新写入版本文件"""
    with open('%s/version.json' % directory, 'w') as f:
        json.dump(data, f)


def write_log(text):
    """记录日志"""
    f = open('%s/HboUpdate.log' % directory, mode='a', encoding='utf-8')
    f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' + "\t" + text + "\n"))
    f.close()


def run():
    while True:
        try:
            online_json = json.loads(
                get_data_by_url("http://test-erp.hbo-erp.com/upload-service/overlay/HboUpdateVersion.json"))
            local_json = read_version_json()
            if online_json == local_json:
                # 运行本地应用
                for program_name in local_json:
                    if local_json.get(program_name).get("is_run"):
                        run_exe(program_name)
            else:
                for program_name in online_json:
                    if local_json.get(program_name):
                        if online_json.get(program_name).get("version") > local_json.get(program_name).get("version"):
                            write_log("更新：%s 版本：%s->%s" % (
                                program_name, local_json.get(program_name).get("version"),
                                online_json.get(program_name).get("version")))
                            write_log("更新地址：%s" % online_json.get(program_name).get("url"))
                            write_log("更新结果：%s" % create_exe_file(online_json.get(program_name).get("url"), program_name))
                    else:
                        write_log(
                            "更新：%s 版本: %s" % (program_name, online_json.get(program_name).get("version")))
                        write_log("更新地址：%s" % online_json.get(program_name).get("url"))
                        write_log("更新结果：%s" % create_exe_file(online_json.get(program_name).get("url"), program_name))

                    if online_json.get(program_name).get("is_auto_run"):
                        set_auto_run(program_name)
                    if online_json.get(program_name).get("is_run"):
                        run_exe(program_name)
                # 更新version
                write_version_json(data=online_json)
        except Exception as e:
            write_log(e.__doc__)
        # sleep 20 minute
        time.sleep(1200)


def set_auto_run(program_name):
    """设置自启动"""
    key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion")
    # 给键添加键值
    new_key = winreg.CreateKey(key, "Run")
    # 设置自启动
    winreg.SetValueEx(new_key, "HboUpdate", 0, winreg.REG_SZ, '"C:\\HboSoft\\%s" hide' % program_name)


if __name__ == '__main__':
    process_list = []
    try:
        process_list = ComputerInfo.get_process_list()
    except Exception as e:
        write_log(e.__doc__)
    if 'HboUpdate.exe' in process_list and process_list.count('HboUpdate.exe') > 2:
        write_log("程序已经在运行")
    else:
        write_log("启动")
        run()
